/*______________________________________________________________________________
 *
 * Copyright 2005 NORSYS
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * (1) Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 * (2) Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 * (3) The name of the author may not be used to endorse or promote
 *     products derived from this software without specific prior
 *     written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *______________________________________________________________________________
 *
 * Created on 27 sept. 2005
 * Author: Arnaud Bailly
 */
package speculoos.core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * A class that allows client-side composition of mapper objects. This class
 * gives the user finer control on the mapper objects it can manipualte and
 * allows him to create aggregate values from the composition of several
 * interconnected mappers.
 * <p />
 * The basic idea is that the result of the computation of one mapper is used as
 * input for another mapper whose result is returned by the compound mapper.
 * This is a simple <em>Composite</em> pattern for mappers.
 * <p />
 * Note that usage of instances of this class may be less efficient than direct
 * encoding of composition operations in the underlying mapper implementation.
 * It should be used with moderation but can provide an easy way to aggregate
 * different sources.
 * 
 * @author nono
 * @version $Id: JoinMapper.java 259 2006-05-23 10:34:50Z /C=FR/ST=Nord/L=Lille/O=Norsys SA/OU=UE/CN=Arnaud Bailly/emailAddress=abailly@norsys.fr $
 */
public class JoinMapper implements Mapper {

    /*
     * left and right mappers
     */
    private Mapper left;
    /*
     * left and right mappers
     */
    private Mapper right;

    /*
     * name of mapper
     */
    private String name = "_join";
    
    /**
     * constructor with twa arguments.
     * 
     * @param left
     * @param right
     */
    public JoinMapper(Mapper left, Mapper right) {
    	this.left = left;
    	this.right = right;
    }
    
    /**
     * default constructor.
     *
     */
    public JoinMapper() {
    	
    }
    /**
	 * @return  Returns the left.
	 */
    public Mapper getLeft() {
        return left;
    }

    /**
	 * @param left  The left to set.
	 */
    public void setLeft(Mapper left) {
        this.left = left;
    }

    /**
	 * @return  Returns the right.
	 */
    public Mapper getRight() {
        return right;
    }

    /**
	 * @param right  The right to set.
	 */
    public void setRight(Mapper right) {
        this.right = right;
    }

    /**
     * This map implementation works as follows:
     * <ol>
     * <li>The status of the <code>left</code> and <code>right</code>
     * mappers this composite aggregates is asserted: This simply means that
     * they must be non null,</li>
     * <li>The <code>left</code> mapper map method is invoked within the
     * environment <code>env</code>,</li>
     * <li>If everything goes well, the <code>right</code> mapper is then
     * invoked with the result of the first mapper as input and in the
     * <em>same</em> environment <code>env</code>:
     * <ul>
     * <li>If the result is not an instance of {@link java.util.Collection},
     * then it is simply passed as is to the second mapper and this result is
     * returned,</li>
     * <li>Else, the collection is iterated over and <em>each</em> element
     * stored in it is used as an invocation input for the <code>right</code>
     * mapper. The return value of this method is the aggregated elements
     * returned by each mappers invocation. Note that the result is
     * <em>flattened</em>.</li>
     * </ul>
     * </li>
     * <li>The result of all this is returned to caller</li>
     * </ol>
     * 
     * @see speculoos.core.Mapper#map(java.lang.Object, java.util.Map)
     */
    public Object map(Object input, Map env) throws MapperException {
        if (left == null || right == null)
            throw new MapperException(
                    "One the components in this composite is null");
        /* first invocation */
        Object res = left.map(input, env);
        if (res instanceof Collection) {
            /* return aggregation of result */
            List ret = new ArrayList();
            for (Iterator it = ((Collection) res).iterator(); it.hasNext();) {
                Object nest = right.map(it.next(), env);
                if (nest instanceof Collection)
                    ret.addAll((Collection) nest);
                else
                    ret.add(nest);
            }
            return ret;
        } else {
            return right.map(res, env);
        }
    }

    
    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj) {
        JoinMapper cm = (JoinMapper) obj;
        if (cm == null)
            return false;
        return (left == null ? cm.left == null : left.equals(cm.left))
                && (right == null ? cm.right == null : right.equals(cm.right));
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        int hl = left == null ? 0 : left.hashCode();
        int hr = right == null ? 0 : right.hashCode();
        return (hl << 13) ^ hr;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return "(" + left.toString() + "," + right.toString() + ")";
    }

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
